//
//  NMNetworkImageNode.swift
//  NetEaseMusic
//
//  Created by SAGESSE on 2020/2/26.
//  Copyright © 2020 SAGESSE. All rights reserved.
//

import UIKit
import AsyncDisplayKit



open class NMNetworkImageNode: ASNetworkImageNode, ASNetworkImageNodeDelegate {
    
    /// The badge node shown in the image.
    open var badge: ASDisplayNode? {
        willSet {
            badge?.removeFromSupernode()
            newValue.map {
                addSubnode($0)
            }
            setNeedsLayout()
        }
    }
    
    /// Indicates whether the CDN acceleration service is enabled.
    open var isCDNAcceleratable: Bool = true
    
        
    open override var defaultImage: UIImage? {
        get { return originDefaultImage }
        set { return originDefaultImage = newValue  }
    }
    
    open override var placeholderFadeDuration: TimeInterval {
        get { return originPlaceholderFadeDuration }
        set { return originPlaceholderFadeDuration = newValue  }
    }
    
    public override init(cache: ASImageCacheProtocol?, downloader: ASImageDownloaderProtocol) {
        super.init(cache: cache, downloader: downloader)
        
        self.originPlaceholderFadeDuration = 0.8
        super.placeholderFadeDuration = 0
        super.placeholderEnabled = true
        self.delegate = self
    }
    

    /// Download and display a new image.
    open override func setURL(_ URL: URL?, resetToDefault reset: Bool) {
        // Save the picture address first.
        originURL = URL

        // When the thumbnail mode is not enabled, ignore.
        guard let newValue = URL, isCDNAcceleratable else {
            return super.setURL(URL, resetToDefault: reset)
        }

        // Don't set the url until layout is complete.
        guard let thumbnailSize = thumbnailSize else {
            return
        }
        
        var components = URLComponents(url: newValue, resolvingAgainstBaseURL: true)
        
        if components?.queryItems == nil {
            components?.queryItems = []
        }
        
        // Reference: https://m.163yun.com/help/documents/66982522786074624
        
        let width = Int(thumbnailSize.width * thumbnailScale)
        let height = Int(thumbnailSize.height * thumbnailScale)
        
        let mode = thumbnailMode
        var format = "webp"
        
        // The webp image size should not exceed 16384.
        if width > 16384 || height > 16384 {
            format = "jpg"
        }

        components?.queryItems?.append(.init(name: "imageView", value: "1"))
        components?.queryItems?.append(.init(name: "type", value: format))
        components?.queryItems?.append(.init(name: "thumbnail", value: "\(width)\(mode)\(height)"))
        
        super.setURL(components?.url ?? newValue, resetToDefault: reset)
    }

    open override func layoutDidFinish() {
        super.layoutDidFinish()
        
        // The thumbnail size is change.
        guard thumbnailSize != bounds.size else {
            return
        }
        thumbnailSize = bounds.size
        thumbnailScale = contentsScale
        setURL(originURL, resetToDefault: false)
    }
    
    open override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
        // When the user has set the badge, must to be display in the right bottom corner.
        let spec = super.layoutSpecThatFits(constrainedSize)
        guard let badge = badge else {
            return spec
        }
        
        let insets = UIEdgeInsets(top: .infinity, left: .infinity, bottom: 3, right: 4)
        return ASOverlayLayoutSpec(child: spec,
                                   overlay: ASInsetLayoutSpec(insets: insets, child: badge))
    }
    
    open override func placeholderImage() -> UIImage? {
        return originDefaultImage ?? super.placeholderImage()
    }
    
    open override func placeholderShouldPersist() -> Bool {
        return image == nil && animatedImage == nil
    }
    
    open func imageNodeWillLoadImage(fromNetwork imageNode: ASNetworkImageNode) {
        super.placeholderFadeDuration = originPlaceholderFadeDuration
    }
    
    open func imageNodeDidLoadImage(fromCache imageNode: ASNetworkImageNode) {
        super.placeholderFadeDuration = 0
    }
        
    private var originURL: URL?
    private var originDefaultImage: UIImage?
    private var originPlaceholderFadeDuration: TimeInterval = 0.5
    
    private var thumbnailSize: CGSize?
    private var thumbnailScale: CGFloat = 1
    private var thumbnailMode: String {
        switch contentMode {
        case .scaleAspectFit:
            return "x"
            
        case .scaleAspectFill:
            return "y"
            
        default:
            return "z"
        }
    }
}


//private func imageWithColor(color:UIColor) -> UIImage? {
//    let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
//    UIGraphicsBeginImageContext(rect.size)
//    color.setFill()
//    UIGraphicsGetCurrentContext()?.fill(rect)
//    let image = UIGraphicsGetImageFromCurrentImageContext()
//    UIGraphicsEndImageContext()
//    return image
//}
//
//
//let placeholderImageX2 = imageWithColor(color: ASDisplayNodeDefaultPlaceholderColor())
